const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const conf = require('../../config/index');

const mysqlConf = conf.dev.mysql;

// 实例化Sequelize

var client = new Sequelize(mysqlConf.database, mysqlConf.user, mysqlConf.pass, {
  host: mysqlConf.host,
  port: mysqlConf.port,
  dialect: 'mysql',
  timezone: '+08:00',
  pool: {
    max: 10,
    min: 0,
    idle: 10000
  },
  logging: (str) => {
    var _str = 'Executing (default):\n' + str.replace('Executing (default):', '') + '\n'
    console.log(_str);
  },
});

// read all schemas and import them into the "db" object
var schemas = {};

fs
  .readdirSync(__dirname + '/schema')
  .filter(function(file) {
    return (file.indexOf('.') !== 0) && (file !== 'index.js');
  })
  .forEach(function(file) {
    var schema = client.import(path.join(__dirname + '/schema', file));
    schemas[schema.name] = schema;
  });

Object.keys(schemas).forEach(function(schemaName) {
  if (schemas[schemaName].hasOwnProperty('associate')) {
    schemas[schemaName].associate(schemas);
  }
});

//export the database
module.exports = schemas;
module.exports.client = client;

module.exports.query = async (sql, replacements) => {
  const result = await client.query(sql, {
    type: client.QueryTypes.SELECT,
    replacements,
  });
  return result;
}
